<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Command;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\App\WorkContact\Contract\ContactFieldContract;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
class InitFieldCommand extends HyperfCommand
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var ContactFieldContract
     */
    private $contactFieldService;

    public function __construct()
    {
        parent::__construct('mochat:init-field');
    }

    public function handle()
    {
        try {
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->contactFieldService = $this->container->get(ContactFieldContract::class);

            $corpIds = [12, 13, 14, 15, 16, 17, 18, 19];
//            $corpIds = [10];
            $initContactFields = $this->contactFieldService->getInitContactFields();
            if (empty($initContactFields)) {
                return;
            }

            foreach ($corpIds as $corpId) {
                $createData = [];
                foreach ($initContactFields as $field) {
                    $createData[] = [
                        'name' => $field['name'],
                        'label' => $field['label'],
                        'type' => $field['type'],
                        'options' => Json::encode($field['options']),
                        'order' => $field['order'],
                        'status' => $field['status'],
                        'is_sys' => $field['isSys'],
                        'field_type' => $field['fieldType'],
                        'corp_id' => $corpId,
                    ];
                }

                if (empty($createData)) {
                    return;
                }

                $this->contactFieldService->createContactFields($createData);
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('初始化企业客户自定义字段失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }

    protected function configure()
    {
        $this->setDescription('初始化客户自定义字段!');
    }
}
